package org.jc.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.jc.gateway.entity.AuthRole;
import org.jc.gateway.redis.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author wanghongqian
 * @date 2024/07/10 14:17
 */
/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";
    private String authRolePrefix = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        // 1.直接跟数据库交互
        // 2.redis缓存
        // 3.redis缓存，诶呦的话，去调用微服务

        String authKey = redisUtil.buildKey(authRolePrefix,loginId.toString());
        String authValue = redisUtil.get(authKey);
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        Type listType = new TypeToken<List<AuthRole>>() {}.getType();
        List<AuthRole> roleList = new Gson().fromJson(authValue,listType);
        List<Long> roleIdList = roleList.stream().map(AuthRole::getId).collect(Collectors.toList());
        List<String> permissionList = new ArrayList<>();
        roleIdList.forEach(roleId -> {
            String permissionKey = redisUtil.buildKey(authPermissionPrefix,roleId.toString());
            String permissionValue = redisUtil.get(permissionKey);
            List<String> permissionTmp = new Gson().fromJson(permissionValue,List.class);
            if(CollectionUtils.isEmpty(permissionTmp)){
                permissionTmp = new ArrayList<>();
            }
            permissionList.addAll(permissionTmp);
        });
        return permissionList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        String authKey = redisUtil.buildKey(authRolePrefix,loginId.toString());
        String authValue = redisUtil.get(authKey);
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        Type listType = new TypeToken<List<AuthRole>>() {}.getType();
        List<AuthRole> roleList = new Gson().fromJson(authValue,listType);
        List<String> roleNameList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());

        return roleNameList;
    }

}
